package com.stock.config;

import com.stock.filter.JwtRequestFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public JwtRequestFilter jwtRequestFilter() {
        return new JwtRequestFilter();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors() // 开启 CORS 支持
                .and()
                .csrf().disable()
                .authorizeRequests()
                // .antMatchers("/user/register","/user/login","/stock/getStockDayData","/stock/getStockYesterdayData").permitAll() // 允许登录接口和获取股票数据接口不需要认证
                .antMatchers("/user/register",
                        "/user/login",
                        "/admin/**",
                        "/swagger-ui/**",
                        "/swagger-resources/**",
                        "/v3/api-docs/**",
                        "/v2/api-docs/**",
                        "/webjars/**").permitAll() // 允许登录接口和注册接口不需要认证
                .anyRequest().authenticated() // 其他接口需要认证
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 使用无状态会话
        // 添加 JWT 过滤器
        http.addFilterBefore(jwtRequestFilter(), UsernamePasswordAuthenticationFilter.class);
    }

}
